import React, { useEffect, useState } from 'react';
import { Upload, Card, Button, PageHeader, Modal, Form, Input, InputNumber } from 'antd';
import { DeleteOutlined, UploadOutlined,ExclamationCircleOutlined } from '@ant-design/icons';
import { getStepList } from '../sysRedux/getAppList';
import { connect } from 'react-redux';
import address from '../address';

let token = '' || localStorage.getItem('token');
const { confirm } = Modal;
const { Meta } = Card;

const CollectionCreateForm = ({ visible, onCreate, onCancel }) => {
    const [form] = Form.useForm();
    const [fileList, setFileList] = useState([]);
    const prop = {
        beforeUpload: file => {
            setFileList([...fileList,file])
            return false;
        },
    };

    return (
        <Modal
            visible={visible}
            title="添加功能"
            okText="添加"
            cancelText="取消"
            onCancel={onCancel}
            onOk={() => {
                form
                    .validateFields()
                    .then((values) => {
                        form.resetFields();
                        onCreate(values,fileList);
                    })
                    .catch((info) => {
                        console.log('Validate Failed:', info);
                    });
            }}
        >
            <Form
                form={form}
                colon={false}
                layout="horizontal"
                name="form_in_modal"
                initialValues={{
                    modifier: 'public',
                }}
            >
                <Form.Item
                    name="text"
                    label="步骤描述"
                    rules={[
                        {
                            required: true,
                            message: '请输入步骤描述!',
                        },
                    ]}
                >
                    <Input />
                </Form.Item>
                <Form.Item
                    name="stepImage"
                    label="步骤图片"
                    valuePropName="fileList1"
                    extra="请选择步骤图片"
                    rules={[{ required: true, message: '请选择步骤图片！' }]}
                >
                    <Upload {...prop}>
                        <Button icon={<UploadOutlined />}>选择图片</Button>
                    </Upload>
                </Form.Item>
                <Form.Item
                    name="dote1"
                    label="定位点1"
                    rules={[
                        {
                            required: true,
                            message: '请输入定位点1',
                        },
                    ]}
                >
                    <InputNumber type="textarea" />
                </Form.Item>
                <Form.Item
                    name="dote2"
                    label="定位点2"
                    rules={[
                        {
                            required: true,
                            message: '请输入定位点2',
                        },
                    ]}
                >
                    <InputNumber />
                </Form.Item>
                <Form.Item
                    name="dote3"
                    label="定位点3"
                    rules={[
                        {
                            required: true,
                            message: '请输入定位点3',
                        },
                    ]}
                >
                    <InputNumber />
                </Form.Item>
                <Form.Item
                    name="dote4"
                    label="定位点4"
                    rules={[
                        {
                            required: true,
                            message: '请输入定位点4',
                        },
                    ]}
                >
                    <InputNumber />
                </Form.Item>
            </Form>
        </Modal>
    );
};

const FunDetails = (props) => {
    const [visible, setVisible] = useState(false);

    //获取步骤列表
    useEffect(() => {
        props.dispatch(getStepList(props.location.pathname));
    }, []);
    //添加步骤
    const onCreate = (values,fileList) => {
        let arr = props.location.pathname.split('/');
        let funName = arr[3] + '_' + arr[4];
        const file = new FormData();
        file.append('table', funName);
        file.append('text', values.text);
        file.append('image', fileList[0]);
        file.append('dote1', values.dote1);
        file.append('dote2', values.dote2);
        file.append('dote3', values.dote3);
        file.append('dote4', values.dote4);
        fetch(address + '/admin/uploadappStep', {
            method: 'POST',
            mode: 'cors',
            headers: {
                'authorization': token
            },
            body: file
        }).then(res => {
            if (res.ok) {
                return res.text()
            } else {
                throw new Error(`status: ${res.status}`)
            }
        }, err => {

        }).then(d => {
            if (d === undefined || d === '') {
                return
            }

        })
            .catch(err => {
                console.log(err)
            })
        setVisible(false);
    };


    const delFun = () => {
        let appname = props.location.pathname.split('/')[3];
        let ename = props.location.pathname.split('/')[4];
        let data = { appname, ename };
        fetch(address + '/admin/deleteAppFunc', {
            method: 'DELETE',
            mode: 'cors',
            headers: {
                'authorization': token
            },
            body: JSON.stringify(data)
        }).then(res => {
            if (res.ok) {
                //只有请求成功才会返回数据
                return res.text()
            } else {
                throw new Error(`status: ${res.status}`)
            }
        }, err => {

        }).then(d => {
            if (d === undefined || d === '') {
                return
            }
        })
            .catch(err => {
                console.log(err)
            })
    }
    const delStep = (step) =>{
        let imgArr = step.image.split('/');
        let appname = imgArr[5];
        let ename = imgArr[6];
        let imgname = imgArr[7];
        let tablename = appname + '_' + ename;
        let data = {appname,ename,imgname,tablename};
        fetch(address+'/admin/deleteAppStep', {
            method : 'DELETE',
            mode : 'cors',
            headers: {
                'authorization':token
            },
            body : JSON.stringify(data)
        }).then(res => {
            if (res.ok) {
                //只有请求成功才会返回数据
                return res.text()
            } else {
                throw new Error(`status: ${res.status}`)
            }
            }, err => {

        }).then(d => {
            if (d === undefined || d === '') {
                return
            }
        })
        .catch(err => {
            console.log(err)
        })
    }

    return (
        <div>

            <PageHeader
                ghost={false}
                subTitle="点击右侧按钮进行功能的删除"
                extra={[
                    <Button
                        key="2"
                        type="danger"
                        onClick={() => {
                            confirm({
                                title: '确认删除此功能？',
                                icon: <ExclamationCircleOutlined />,
                                content: '删除后无法进行恢复',
                                okText: '删除',
                                cancelText: '取消',
                                onOk() {
                                    delFun()
                                },
                                onCancel() {
                                    console.log('取消删除');
                                },
                            });
                        }}
                    >删除该功能</Button>
                ]}
            >
                <Button
                    key="1"
                    type="primary"
                    onClick={() => {
                        setVisible(true);
                    }}
                >添加新步骤</Button>

            </PageHeader>

            <CollectionCreateForm
                visible={visible}
                onCreate={onCreate}
                onCancel={() => {
                    setVisible(false);
                }}
            />

            {
                props.stepdata.map((item, index) => (
                    <Card
                        key={index}
                        hoverable
                        style={{ width: 240, display: 'inline-block', margin: '10px', border: '1px #4C64D6 solid', overflow: 'hidden' }}
                        cover={<img alt="example" src={item.image} />}

                        actions={[
                            <Button
                                type="link"
                                danger
                                onClick={()=>{
                                    confirm({
                                        title: '确认删除此步骤？',
                                        icon: <ExclamationCircleOutlined />,
                                        content: '删除后无法进行恢复',
                                        okText:'删除',
                                        cancelText:'取消',
                                        onOk() {
                                            delStep(item);
                                        },
                                        onCancel() {
                                          console.log('取消删除');
                                        },
                                      });
                                }}
                            >
                                <DeleteOutlined /> 删除
                            </Button>
                        ]}

                    >
                        <Meta description={item.text} />
                    </Card>
                ))
            }
        </div>
    )
}

const mapStateToProps = (state) => ({
    stepdata: state.funSteplist.data
})

export default connect(mapStateToProps)(FunDetails);

